package com.example.consistenthash.two;

import com.example.consistenthash.stretagy.Fnv132HashStrategy;
import com.example.consistenthash.stretagy.HashStrategy;
import com.example.consistenthash.stretagy.JdkHashStrategy;

import java.util.ArrayList;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;

public class ConsistentHash2 {

    private static String[] servers = new String[]{"192.168.0.1:8080", "192.168.0.2:8080", "192.168.0.3:8080", "192.168.0.4:8080"};

    private static SortedMap<Integer, String> sortedMap = new TreeMap<>();

    private static HashStrategy hashStrategy = new Fnv132HashStrategy();

    static {

        for (String server : servers) {
            int hash = hashStrategy.hash(server);
            System.out.println("[" + server + "]加入集合中, 其HashCode为" + hash);
            sortedMap.put(hash, server);
        }
    }

    public static String getServer(String key) {
        int hash = hashStrategy.hash(key);
        SortedMap<Integer, String> tailMap = sortedMap.tailMap(hash);
        if (tailMap.isEmpty()) {
            Integer firstKey = sortedMap.firstKey();
            return sortedMap.get(firstKey);
        } else {
            Integer firstKey = tailMap.firstKey();
            return tailMap.get(firstKey);
        }
    }

    public static void main(String[] args) {
        String[] nodes = {"127.0.0.1:8080", "255.255.255.0:9090", "10.36.46.23:6666", "192.168.0.5:8080"};
        for (int i = 0; i < nodes.length; i++)
            System.out.println("[" + nodes[i] + "]的hash值为" +
                    hashStrategy.hash(nodes[i]) + ", 被路由到结点[" + getServer(nodes[i]) + "]");
    }
}
